<template>
  <div class="app-container">
 
    <span style="float: right;">
      <!-- <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip> -->
      <el-button type="primary" @click="activeReturnDate('update')" size="small" plain round>修改还箱日期</el-button>
      <el-button type="primary" @click="activeReturnDate('add')" size="small" plain round>添加还箱日期</el-button>
      <el-button type="primary" @click="param.dialogVisible = true" size="small" plain round>还箱</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" style="width: 100%;" @pageChange="onTablePageChange" @activDelete="activDelete"
      @showInfo="showInfo" @activeRemark="activeRemark" @uploadReturn="uploadReturn" @handleEdit="handleEdit"  @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 还箱记录详情 -->
    <el-drawer v-model="param.drawer" v-if="param.drawer" :with-header="false">
      <returnRecord ref="detaiInfoRef"></returnRecord>
    </el-drawer>

    <!-- 还箱日期 -->
    <el-dialog v-model="param.dialogVisible1" :title="thisOpt == 'add' ? '添加还箱日期' : '修改还箱日期'" width="300">
      <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-date-picker v-model="param.returnDateSync" type="date" style="text-align: center;"></el-date-picker>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 40px;">

        <el-button type="primary" @click="handleReturnDate" plain style="width:100px">确定</el-button>
      </div>
    </el-dialog>

    <!-- 备注 -->
    <el-dialog v-model="param.dialogVisibleRemark" :title="thisOpt == 'update' ? '修改备注' : '添加备注'" width="300">
      <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-input v-model="param.remarkValSync" type="textarea" show-word-limit maxlength="200" rows="2"></el-input>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 40px;">
        <el-button type="primary" @click="handleRemark" plain style="width:100px">确定</el-button>
      </div>
    </el-dialog>
    <!-- warning-->
    <el-dialog v-model="param.dialogVisible" title="还箱提示" width="500">
      <span style="color: chocolate;">您确认要还箱吗？</span>
      <p>请确保还箱记录信息正确</p>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="param.dialogVisible = false">取消</el-button> -->
          <el-button @click="handleReturnBox">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- upload -->
    <el-dialog v-model="param.dialogPitchUploadVisible" title="上传附件" style="width: 400px;">
      <uploadFile ref="uploadFileRef" :limitForce="5" :limit="6" :type="'zip_rar_jpg_png'" @getImgList="getImgList">
      </uploadFile>
      <div style="width: 100%;text-align: center;">
        <el-button @click="handlePitchUpload" type="primary">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
// import { formatDate } from '@/utils'
import returnRecord from '@/views/components/huanXiangManage/returnRecord.vue'
import Table from '@/components/table'
import uploadFile from '@/components/upload/index.vue'
import { getTable, getDetailTable, getReturnData, updateReturnMark, updateReturnDate, updateDetailFile, finishReturnBoxDetail,getretunDetailData } from '@/api/orderManage/returnBoxDetail'
import { computed, onMounted, onActivated, reactive, ref,nextTick,inject } from 'vue';
import {
  Plus,
  Delete,
  Edit,
  Message,
  Search,
  Download,
  Upload,
  Refresh,
  UploadFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { set } from '@vueuse/core';
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
import { useRoute } from 'vue-router'
const isAgent=inject('isAgent') //当前等角色  true 货代角色  false 集装箱公司角色
const formData = inject('formData')

const param = reactive({
  value1: [],
  boxInfo: { code: '123456789', type: "40HQ", info: "无" },
  pageNum: 0,
  pageSize: 10,
  dialogTableVisible: false,
  drawer: false,
  dialogEditVisible: false,
  dialogVisible: false,
  dialogPathVisible: false,
  statusOptions: [ //5-未还   10-已还  15-已买/已卖
    { value: '5', label: '未还', },
    { value: '10', label: '已还', },
    { value: '30', label: '已卖', },
  ],
  statusColor: { 5: 'red', 10: '#22A86D', 30: '#2158F3' },

  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
   { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '5', label: '全新', },
    // { value: '20', label: '混提(次新或者适货)', },
  ],
  returnDateSync: null
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'containerNo', colWidth: '100', title: '箱号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'boxType', colWidth: '60', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    // { key: 'boxCondition', colWidth: '60', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'returnDate', colWidth: '120', title: '还箱日期', showEditPen: true, command: 'handleEdit', type: 'date', isCheck: true },
    // { key: 'createTime', colWidth: '80', title: '创建日期', type: 'dateTime', isCheck: true },
    { key: 'overdueDays', colWidth: '80',title: '超期天数', type: 'text', isCheck: true },
    { key: 'yardName',colWidth: '120', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'agentName', colWidth: '120', title: '客户', type: 'text', isCheck: true },
    { key: 'status', title: '状态',colWidth: '60', type: 'filter', filter: { 5: '未还', 10: '已还', 30: '已卖' }, cFilter: param.statusColor, isCheck: true },
    {
      key: 'remark',
      colWidth: '60',
      title: '备注',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: 'Plus',
          command: 'activeRemark',
          isShow: (row: any) => {
            return !row.remark && row.returnBoxStatus != 20;
            //returnBoxStatus 还箱单状态: 5-已发放 10-已下载 15-还箱中 20-已完成 25-已过期
          },
        },
        {
          // icon: 'Edit',
          command: 'activeRemark',
          showOnlyKey: true,
          // isReadOnly: (row: any) => {
          //   return row.returnBoxStatus != 20;
          // },
          isShow: (row: any) => {
            return row.remark;
          },
        },
      ],
    },

    {
      key: 'operate',
      colWidth: '80',
      title: '上传附件',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: 'Upload',
          command: 'uploadReturn',
          name: '上传',
          isShow: (row: any) => {
            return row.returnBoxStatus != 20
          },
        },
      ],
    },
    { key: 'orderNo', colWidth: '120',title: '订单号', type: '<a>', isCheck: true },
    { key: 'returnBoxNo',colWidth: '110', title: '还箱单号', type: '<a>', isCheck: true },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: false, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});
const orderTypeval = ref("")
onMounted(() => {
  nextTick(() => {
    if(isAgent.value){
          orderTypeval.value = "5"
    }else{
           orderTypeval.value = "10"
    }
    getTableData()
    })

})

const getTableData = () => {
  const { container, containerList } = formatContainerNo(param.containerNo);    
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    orderType:orderTypeval.value,
    returnBoxNo: param.returnBoxNo,
    boxType: param.boxType,
    orderNo: param.orderNo,
    agentName: param.agentName,
    yardName: param.yardName,
    status: param.status,
  }
  if (param.returnDate) {
    data.beginReturnDate = param.returnDate[0]
    data.endReturnDate = param.returnDate[1]
  }
  getretunDetailData(formData.value.id).then((res: any) => {
    console.log("resresresres",res)
    table.data = res.data;
    // table.config.total = res.data.total;
  })
}
function handleReSet() {
  param.containerNo = null
  param.returnBoxNo = null
  param.boxType = null
  param.orderNo = null
  param.returnDate = null
  param.agentName = null
  param.status = null
  param.yardName = null
  getTableData()
}

//增删改查-----------
//删除  
const activDelete = (row: any) => {
  param.dialogVisible = true;
};
const tableRef = ref({multipleSelection:[]});
const handleDelete = () => {
  console.log(tableRef.value.multipleSelection)
  const selection = tableRef.value.multipleSelection
  if (selection.length == 0) {
    return
  }
  selection.forEach(async (item: any) => {
    await deletePackingDetail(item.id)
  })
  getTableData();
  // if (res.code == 200) {
  //   getTableData();
  // }
};
const detaiInfoRef=ref()
//详情
const showInfo = (row: any) => {
  getReturnData(row.id).then((res: any) => {
    rowData.value = res.data
    param.drawer = true;
    nextTick(() => {
      detaiInfoRef.value.openBox(rowData.value)   
      })   

  })
};

//upload
const uploadReturn = (row: any) => {
  // console.log(row)
  param.dialogPitchUploadVisible = true;
  rowData.value = row
};
const imgList = ref([])
const getImgList = (file: any, row: any) => {
  imgList.value = file
};
const uploadFileRef = ref();
const handlePitchUpload = () => {
  if (imgList.value.length == 0) {
    return ElMessage.warning('请先上传文件！')
  }
  const data = {
    id: rowData.value.id,
    detailFileList: JSON.stringify(imgList.value)
  }
  updateDetailFile(data).then((res: any) => {
    ElMessage.success('上传成功！')
    param.dialogPitchUploadVisible = false;
    uploadFileRef.value.clearFiles()
  })
};

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

// 修改还箱日期-单行
const handleEdit = (row: any) => {
  tableRef.value.multipleSelection = [row]
  param.returnDateSync = row.returnDate
  thisOpt.value = row.returnDate ? 'update' : 'add'
  param.dialogVisible1 = true;
  console.log(tableRef.value.multipleSelection)
};

//修改还箱日期-批量
let thisOpt = ref('');
const activeReturnDate = (opt: string) => {
  if (validateSelect()) return
  thisOpt.value = opt
  param.dialogVisible1 = true;
};

// 修改还箱日期-确定
const handleReturnDate = () => {
  if (validateSelect()) return
  if (!param.returnDateSync) {
    return ElMessage.warning('请选择日期！')
  }
  // if (new Date(param.returnDateSync) > new Date()) {
  //   return ElMessage.warning('选择日期必须 小于等于 当前日期！')
  // }
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const selection = checkAllItem
  const index = selection.findIndex((item: any) => {
    return new Date(new Date(item.createTime).setHours(0, 0, 0, 0)) > new Date(param.returnDateSync)
  })
  if (index >= 0) {
    return ElMessage.warning('选择日期必须 大于等于 还箱单/还箱令/还箱属的创建日期！')
  }
  const data: any = []
  selection.forEach((item: any) => {
    data.push({ id: item.id, returnDate: param.returnDateSync })
  })
  updateReturnDate(data).then((res: any) => {
    param.dialogVisible1 = false
    getTableData();
  })
};

// 确认还箱
const handleReturnBox = () => {
  if (validateSelect()) return
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const selection = checkAllItem
  const data: any = []
  selection.forEach((item: any) => {
    data.push(item.id)
  })
  finishReturnBoxDetail(data).then((res: any) => {
    param.dialogVisible = false;
    setTimeout(() => { // 延时执行 数据刷新存在延迟，等待接口下个版本更新
      getTableData();
    }, 1000);
  })
};

//备注
const rowData = ref({});
const activeRemark = (row: any) => {
  if (row.returnBoxStatus == 20) return ElMessage.warning('还箱单已完成不可修改')  // 还箱单，已完成不可再修改
  rowData.value = row;
  thisOpt.value = row.remark ? 'update' : 'add';
  if (row.remark) {
    param.remarkValSync = row.remark
  }else{
    param.remarkValSync=''
  }
  param.dialogVisibleRemark = true;
};
//添加|修改备注
const handleRemark = (row: any) => {
  // thisOpt.value = row.remark ? 'update' : 'add';
  const data = { id: rowData.value.id, "remark": param.remarkValSync }
  updateReturnMark(data).then((res: any) => {
    param.dialogVisibleRemark = false;
    getTableData()
  })
};


// other
// 验证有选择
const validateSelect = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const selection = checkAllItem
  if (selection.length == 0) {
    ElMessage({
      message: (`请选择要操作的记录`),
      type: 'warning'
    })
    return true
  }
  return false
};



const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getDetailTable({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

</script>

<style scoped lang="scss">
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
</style>
